//*************************************************************************************
//* 作    者： zouhunter
//* 创建时间： 2021-10-04 05:08:35
//* 描    述： 

//* ************************************************************************************
using UnityEngine;
using UnityEngine.UI;

public class LocalizationText : MonoBehaviour
{
    [SerializeField, UFrame.DefaultComponent]
    protected Text m_text;
    [SerializeField]
    protected string m_key;
    [SerializeField]
    protected string m_format;

    private void OnEnable()
    {
        LanguageAgent.Instance.onLanguageChanged += OnLanguageChanged;
        OnLanguageChanged();
    }

    private void OnDisable()
    {
        LanguageAgent.Instance.onLanguageChanged -= OnLanguageChanged;
    }

#if UNITY_EDITOR
    protected void ShowText(SystemLanguage language)
    {
        UFrame.TableCfg.TableCtrl tableCtrl = new UFrame.TableCfg.TableCtrl();
        tableCtrl.LoadTable<UFrame.TableCfg.LocalizationCfg>(0, "Tables/localization_cfg.csv", (table) =>
        {
            using (var enumerator = table.GetListEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    var config = enumerator.Current;

                    if (config.key == m_key)
                    {
                        switch (language)
                        {
                            case SystemLanguage.English:
                                SetText(config.en);
                                break;
                            case SystemLanguage.Chinese:
                            default:
                                SetText(config.cn);
                                break;
                        }
                        break;
                    }
                }
            }
        });
    }

    [ContextMenu("显示语言/中文")]
    void ShowChinese()
    {
        ShowText(SystemLanguage.Chinese);
    }

    [ContextMenu("显示语言/英文")]
    void ShowEnglish()
    {
        ShowText(SystemLanguage.English);
    }
#endif

    private void OnLanguageChanged()
    {
        if (!m_text)
            return;

        var textValue = LanguageAgent.Instance.GetTextByKey(m_key);
        SetText(textValue);
    }

    private void SetText(string textValue)
    {
        if (string.IsNullOrEmpty(m_format))
        {
            m_text.text = textValue;
        }
        else
        {
            m_text.text = m_format.Replace("{0}", textValue);
        }
    }


    public static void Binding(Text target, string keyCode, string format = null)
    {
        var localizationText = target.gameObject.MustComponent<LocalizationText>();
        localizationText.m_key = keyCode;
        localizationText.m_format = format;
    }
}
